package org.ccay.core.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Matcher;

import org.ccay.core.ioc.Ccay;
import org.ccay.core.ioc.CcayApplicationContext;
import org.ccay.core.orm.ITagHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

/**
 * 抽象的字符串替换接口 主要是添加了$(group)方法来替代matcher.group(group)
 * @see org.ccay.core.util.StringUtil
 */
public abstract class AbstractReplaceCallback implements IReplaceCallback {

	protected Matcher matcher;

	final public String replace(String text, int index, Matcher matcher) {
		this.matcher = matcher;
		try {
			return doReplace(text, index, matcher);
		} finally {
			this.matcher = null;
		}
	}

	/**
	 * 将text转化为特定的字串返回
	 * 
	 * @param text
	 *            指定的字符串
	 * @param index
	 *            替换的次序
	 * @param matcher
	 *            Matcher对象
	 * @return
	 */
	public abstract String doReplace(String text, int index, Matcher matcher);

	/**
	 * 将text转化为特定的字串返回
	 * 
	 * @param text
	 *            指定的字符串
	 * @param index
	 *            替换的次序
	 * @param matcher
	 *            Matcher对象
	 * @param bean
	 *            标签处理器bean
	 * @param paramObject           
	 * 			     参数对象
	 * @return
	 */
	public String doReplaceHandler(String text, int index, Matcher matcher,String bean,Object paramObject) {
		CcayApplicationContext context = Ccay.getContext();

		ITagHandler tagHandler = null;

		Element root = null;
		StringReader readerStr = null;
		try {
			// 生成Element对象
			readerStr = new StringReader(text);
			InputSource source = new InputSource(readerStr);
			Document doc = DomUtil.loadDocument(source, null);

			root = doc.getDocumentElement();
			tagHandler = context.getBean(bean, ITagHandler.class);

			// 调用ITagHandler接口
			if (tagHandler != null) {
				return tagHandler.handle(root, text, paramObject);
			}

		} catch (IOException e) {
			throw new IllegalArgumentException("Parse tag text fail. tag:"
					+ text, e);
		}finally{
			StreamUtil.closeStreams(readerStr);
		}

		return text;

	} 
}
